/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.prashant.sqlduniya.dashboard;

import java.util.Collections;
import javax.swing.JComboBox;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Lookup;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.prashant.sqlduniya.sqlmanager.DBConnectionManager;
import org.prashant.sqlduniya.sqlmanager.DBNode;
import org.prashant.sqlduniya.sqlmanager.TableBean;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.prashant.sqlduniya.dashboard//DBTree//EN",
autostore = false)
@TopComponent.Description(preferredID = "DBTreeTopComponent",
iconBase = "org/prashant/sqlduniya/dashboard/table_1.png",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "explorer", openAtStartup = true)
@ActionID(category = "Window", id = "org.prashant.sqlduniya.dashboard.DBTreeTopComponent")
@ActionReference(path = "Menu/Window" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_DBTreeAction",
preferredID = "DBTreeTopComponent")
@Messages({
    "CTL_DBTreeAction=DBTree",
    "CTL_DBTreeTopComponent=DB Viewer",
    "HINT_DBTreeTopComponent=This is a DB Viewer window"
})
public final class DBTreeTopComponent extends TopComponent implements ListSelectionListener {

    private static DBConnectionManager cm;
    private InstanceContent content = new InstanceContent();
    private TableNodeListModel listModel = null;
    private DBNode dBNode;
    
    public DBNode getdBNode() {
        return dBNode;
    }

    public JComboBox getCbCatalog() {
        return cbCatalog;
    }

    public void setdBNode(DBNode dBNode) {
        DBNode old = this.dBNode;
        this.dBNode = dBNode;
        firePropertyChange("dBNode", old, dBNode);
    }

    public DBTreeTopComponent() {
        initComponents();
        setName(Bundle.CTL_DBTreeTopComponent());
        setToolTipText(Bundle.HINT_DBTreeTopComponent());
        putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);


        jListTable.getSelectionModel().addListSelectionListener(this);

        associateLookup(new AbstractLookup(content));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListTable = new javax.swing.JList();
        ListCellRenderer oldRenderer = jListTable.getCellRenderer();
        jListTable.setCellRenderer(new TableNodeListRenderer(oldRenderer));
        cbCatalog = new javax.swing.JComboBox();
        ListCellRenderer cbOldRenderer = cbCatalog.getRenderer();
        cbCatalog.setRenderer(new SchemaListRenderer(cbOldRenderer));

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${dBNode.tables}");
        org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, jListTable);
        jListBinding.setDetailBinding(org.jdesktop.beansbinding.ELProperty.create("${label}"));
        bindingGroup.addBinding(jListBinding);

        jScrollPane2.setViewportView(jListTable);

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${dBNode.schemas}");
        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, cbCatalog);
        bindingGroup.addBinding(jComboBoxBinding);

        cbCatalog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbCatalogActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
                    .addComponent(cbCatalog, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbCatalog, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
                .addGap(23, 23, 23))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void cbCatalogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbCatalogActionPerformed
        if (cbCatalog.getSelectedItem() == null) {
            return;
        }
        Runnable work = new Runnable() {

            public void run() {
                final String catalog = cbCatalog.getSelectedItem().toString();

                ProgressHandle handle = ProgressHandleFactory.createHandle("Loading Tables");
                try {
                    handle.start();

                    cm.getActiveConnection().setCatalog(catalog);

                    dBNode.populateTables(cm.loadTables(cm.getActiveConnection(),
                            catalog),
                            catalog);

                    listModel = new TableNodeListModel(dBNode.getTables());
                    jListTable.setModel(listModel);

                    handle.finish();
                } catch (Exception ex) {
                    handle.finish();
                }
            }
        };
        SwingUtilities.invokeLater(work);

    }//GEN-LAST:event_cbCatalogActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbCatalog;
    private javax.swing.JList jListTable;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        cm = Lookup.getDefault().lookup(DBConnectionManager.class);
    }

    @Override
    public void componentClosed() {
        cm = null;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {
            TableBean table = (TableBean) listModel.getElementAt(jListTable.getSelectedIndex());
            content.set(Collections.singleton(table), null);
        }
    }
}
